#!/usr/bin/env python
#coding:utf-8
import pygtk
import gtk
import gtrans
import dbmanger,open_zip
import threading
import time
import gobject



class MyThread(threading.Thread):
    def __init__ (self,textView):
        super(MyThread, self).__init__()
        self.textView = textView
        #self.str2 = ''
        self.str1 = ''
        self.quit = False
    def update_text_view(self,str2):
        self.textView.get_buffer().set_text(str2)
    def run(self):
        while not self.quit:
            if(len(self.str1)): 
                str2 = gtrans.Translate().Start(self.str1)
                gobject.idle_add(self.update_text_view,str2)
                self.str1 = ''
            time.sleep(0.1)


           
class EntryExample:
    def changed(self, vadjust):
        """autoscroll"""
        if not hasattr(vadjust, "need_scroll") or vadjust.need_scroll:
            vadjust.set_value(vadjust.upper-vadjust.page_size)
            vadjust.need_scroll = True

    def value_changed (self, vadjust):
        """autoscroll"""
        vadjust.need_scroll = abs(vadjust.value + vadjust.page_size - vadjust.upper) < vadjust.step_increment
    def trans_callback(self,widget):
        '''
        try:
            text = self.entry.get_text()
            if len(text):
                print text        
                #print gtrans.Translate().Start(text)
                self.textview1.get_buffer().set_text(gtrans.Translate().Start(text))
        except:
            print 'error'    
        '''    
        # text = self.entry.get_text()
        # if len(text):
            # print text        
            # print gtrans.Translate().Start(text)
            # self.textview1.get_buffer().set_text(gtrans.Translate().Start(text))
        text = self.entry.get_text()
        if len(text):
            t.str1 = text
            
 
    def fav_callback(self,widget):     
        str1 = self.entry.get_text()
        buffer1 = self.textview1.get_buffer()
        str2 = buffer1.get_text(buffer1.get_start_iter(),buffer1.get_end_iter())
        print 32,type(str2)
        dbmanger.DbManger().insert_word(str1,str2)
        self.SetList()
        open_zip.savedb()
        
        
    def enter_callback(self, widget, entry):
        #entry_text = entry.get_text()
        #print "Entry contents: %s\n" % entry_text
        self.trans_callback(widget)
    def entry_toggle_editable(self, checkbutton, entry):
        entry.set_editable(checkbutton.get_active())
    def entry_toggle_visibility(self, checkbutton, entry):
        entry.set_visibility(checkbutton.get_active())
    def selection_made(self, clist, row, column, event, data=None):
        #text = clist.get_text(row, column)
        self.textview1.get_buffer().set_text(dbmanger.unquote_text(str(self.list1[row][2])))
        #print ("You selected row %d,and the text in this cell is %s\n" % (row, text))
            
    def __init__(self):
        # create a new window
        self.x = 400
        self.y = 400
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_size_request(self.x, self.y)
        window.set_title("gtrans")
        window.set_position(gtk.WIN_POS_CENTER);
        window.connect("delete_event", lambda w,e: gtk.main_quit())

        
        hbox_1 = gtk.HBox(False, 0)
        hbox_1.show()
        window.add(hbox_1)
        scrolled_window = gtk.ScrolledWindow()
        scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
        hbox_1.pack_start(scrolled_window, gtk.TRUE, gtk.TRUE, 0)
        scrolled_window.show()
        self.clist = gtk.CList( 2, ["word","time"])
        self.clist.connect("select_row", self.selection_made)
        self.clist.set_shadow_type(gtk.SHADOW_OUT)
        self.clist.set_column_width(0, 100)
        scrolled_window.add(self.clist)
        self.clist.show()
        
        
        
        vbox = gtk.VBox(False, 0)
        hbox_1.pack_start(vbox, gtk.FALSE, gtk.FALSE, 0)
        #vbox.set_size_request(20,20)
        vbox.show()
        entry = gtk.Entry()
        entry.set_max_length(50)
        
        entry.connect("activate", self.enter_callback, entry)
        #entry.set_text("hello")
        #entry.insert_text(" world", len(entry.get_text()))
        #entry.select_region(0, len(entry.get_text()))
        vbox.pack_start(entry, True, False, 0)
        entry.show()
        
        self.entry = entry
        
        scroll = gtk.ScrolledWindow()
        vbox.pack_start(scroll, True, False, 0)
        scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        #auto scroll
        scroll.get_vadjustment().connect("changed", self.changed)
        scroll.get_vadjustment().connect("value-changed", self.value_changed)
        buffer = gtk.TextBuffer()               
        self.textview1 = gtk.TextView(buffer)
        scroll.add(self.textview1)
        self.textview1.set_wrap_mode(gtk.WRAP_CHAR)
        self.textview1.set_size_request(self.x/2, self.y/4)      
        self.textview1.show()
        scroll.show()
                       
        hbox = gtk.HBox(True, 0)
        vbox.pack_start(hbox, True, False, 0)
        hbox.show()
        
        check = gtk.CheckButton("Editable")
        hbox.pack_start(check, True, True, 0)
        check.connect("toggled", self.entry_toggle_editable, entry)
        check.set_active(True)
        check.show()
        
        check = gtk.CheckButton("Visible")
        hbox.pack_start(check, True, True, 0)
        check.connect("toggled", self.entry_toggle_visibility, entry)
        check.set_active(True)
        check.show()
        
        hbox1 = gtk.HBox(True, 0)
        #hbox1.set_size_request(self.x,self.y/8)
        vbox.pack_start(hbox1, True, False, 0)
        hbox1.show()
        
        button = gtk.Button(stock=gtk.STOCK_CLOSE)
        button.connect("clicked", lambda w: gtk.main_quit())
        hbox1.pack_start(button, False, False, 0)
        #button.set_flags(gtk.CAN_DEFAULT)
        #button.grab_default()
        button.show()
        
        button_trans = gtk.Button('translate')
        button_trans.connect("clicked", self.trans_callback) 
        hbox1.pack_start(button_trans, False, False,0)
        button_trans.show()
        
        button_fav = gtk.Button('fav')
        button_fav.connect("clicked", self.fav_callback)        
        hbox1.pack_start(button_fav, False, False,0)
        button_fav.show()
        
        
        
        self.SetList()
        entry.grab_focus()
        
        
        
        window.show()
    def SetList(self):
        self.clist.clear()
        self.list1=dbmanger.DbManger().GetWordAndMeaning()
        for each in self.list1:
            pass
            #print len(each)
            #print each[0:3]
            self.clist.append(each[0:2])
            #print each[0]
        
        
def main():
    gtk.main()
    t.quit = True
    print t.quit,202
    return 0

if __name__ == "__main__":
    gobject.threads_init()
    open_zip.exactdb()
    entryEx = EntryExample() 
    #entryEx.textview1 
    t = MyThread(entryEx.textview1)
    t.start()
    main()
    #open_zip.savedb()